<!-- 籍贯组件 -->
<template>
	<my-input disabled v-bind="$attrs">
		<template #append v-if="!($attrs.disabled || $attrs.detail)">
			<el-popover placement="top-start" title="选择籍贯" :width="240" :visible="visible">
				<my-form
					label-width="40px"
					:model="data"
					:formItem="[
						{
							label: '省份',
							prop: 'province',
							itemType: 'select',
							list: provinceList,
							onChange: (val) => {
								Object.assign(data, {
									city: '',
									cityName: '',
									area: '',
									areaName: ''
								});
								cityList = [];
								countyList = [];
								val && getChinaCity(val, 1);
							},
							onGetLabel: (val) => {
								data.provinceName = val || '';
							}
						},
						{
							label: '城市',
							prop: 'city',
							itemType: 'select',
							list: cityList,
							onChange: (val) => {
								Object.assign(data, {
									area: '',
									areaName: ''
								});
								countyList = [];
								val && getChinaCity(val, 2);
							},
							onGetLabel: (val) => {
								data.cityName = val || '';
							}
						},
						{
							show: levels == 3,
							label: '区县',
							prop: 'area',
							itemType: 'select',
							list: countyList,
							onGetLabel: (val) => {
								data.areaName = val || '';
							}
						}
					]"
				/>
				<div class="flex justify-end">
					<my-button @click="visible = false"> 取消 </my-button>
					<my-button type="primary" @click="clickFn"> 确定 </my-button>
				</div>
				<template #reference>
					<el-button
						icon="Search"
						@click="
							() => {
								cityList = [];
								visible = true;
							}
						"
					/>
				</template>
			</el-popover>
		</template>
	</my-input>
</template>

<script setup>
import { lcareaData } from '@/api/system';

defineProps({
	levels: {
		type: [String, Number],
		default: 2
	}
});
const attrs = useAttrs(),
	emits = defineEmits(['change']);

function clickFn() {
	attrs['onUpdate:modelValue'](data.value.provinceName + data.value.cityName + data.value.areaName || '');
	emits('change', data.value);
	visible.value = false;
}

// 省市县
const data = ref({}),
	provinceList = ref([]), // 省份
	cityList = ref([]), // 市
	countyList = ref([]), // 县/区
	visible = ref(false);

getChinaCity();
function getChinaCity(parentCode = 0, levels = 0) {
	lcareaData({ levels, parentCode }).then((res) => {
		let dataList = levels === 2 ? countyList : levels === 1 ? cityList : provinceList;
		dataList.value = res.data.map((item) => {
			return {
				dictLabel: item.name,
				dictValue: String(item.code)
			};
		});
	});
}
</script>
